/*(C) 2007-2012 Alibaba Group Holding Limited.	 *This program is free software; you can redistribute it and/or modify	*it under the terms of the GNU General Public License version 2 as	* published by the Free Software Foundation.	* Authors:	*   junyu <junyu@taobao.com> , shenxun <shenxun@taobao.com>,	*   linxuan <linxuan@taobao.com> ,qihao <qihao@taobao.com> 	*/	package com.taobao.tddl.common.mockdatasource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.taobao.tddl.common.exception.runtime.NotSupportException;
import com.taobao.tddl.common.mockdatasource.MockDataSource.ExecuteInfo;

public class MockStatement implements Statement {
	private static final Log logger = LogFactory.getLog(MockStatement.class);
	protected MockDataSource mds;
	protected String sql;
	protected List<String> sqls = new ArrayList<String>();
	//protected UpdateHandler updateHandler;
	protected int queryTimeOut;
	protected int fetchSize;
	protected int maxRows;

	public MockStatement(String method, MockDataSource mockDataSource, String sql) {
		this.sql = sql;
		this.mds = mockDataSource;
		MockDataSource.record(new ExecuteInfo(this.mds, method, null, null));
	}

	public MockStatement(String method, MockDataSource mockDataSource) {
		this.mds = mockDataSource;
		MockDataSource.record(new ExecuteInfo(this.mds, method, null, null));
	}

	public void addBatch(String sql) throws SQLException {
		mds.checkState();
		this.sqls.add(sql);
	}

	public void cancel() throws SQLException {
		mds.checkState();
		throw new NotSupportException("");
	}

	public void clearBatch() throws SQLException {
		mds.checkState();
		this.sqls.clear();
	}

	public void clearWarnings() throws SQLException {
		throw new NotSupportException("");
	}

	private int closeInvokingTimes = 0;

	public void close() throws SQLException {
		mds.checkState();
		closeInvokingTimes++;
	}

	private boolean isClosed;

	protected void checkClosed() throws SQLException {
		if (isClosed)
			throw new SQLException("closed");
	}

	private boolean success = true;
	private int executeSqlInvokingTimes = 0;

	public boolean execute(String sql) throws SQLException {
		mds.checkState();
		this.sql = sql;
		executeSqlInvokingTimes++;
		logger.warn("[execute(String)]" + sql);
		MockDataSource.record(new ExecuteInfo(this.mds, "execute", this.sql, null));
		return success;
	}

	public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
		mds.checkState();
		this.sql = sql;
		executeSqlInvokingTimes++;
		logger.warn("[execute(String,int)]" + sql);
		MockDataSource.record(new ExecuteInfo(this.mds, "execute_sql_int", this.sql, null));
		return success;
	}

	protected ExecuteHandler executerHandler = new ExecuteHandler() {

		public ResultSet execute(String method, String tsql) {
			sql = tsql;
			executeSqlInvokingTimes++;
			logger.warn("[executerHandler]" + sql);
			MockDataSource.record(new ExecuteInfo(MockStatement.this.mds, method, MockStatement.this.sql, null));
			return new MockResultSet(mds, MockDataSource.popPreData());
		}

		public boolean executeSql(String method, String tsql) {
			sql = tsql;
			executeSqlInvokingTimes++;
			logger.warn("[executerHandler]" + sql);
			MockDataSource.record(new ExecuteInfo(MockStatement.this.mds, method, MockStatement.this.sql, null));
			return true;
		};

	};

	public boolean execute(String sql, int[] columnIndexes) throws SQLException {
		mds.checkState();
		return executerHandler.executeSql("execute#sql_int[", sql);
	}

	public boolean execute(String sql, String[] columnNames) throws SQLException {
		mds.checkState();
		return executerHandler.executeSql("execute#sql_string[", sql);
	}

	public int[] executeBatch() throws SQLException {
		mds.checkState();
		logger.warn("[executeBatch]" + sql);
		//throw new NotSupportException("");
		MockDataSource.record(new ExecuteInfo(this.mds, "executeBatch", this.sql, null));
		return new int[] { -1, -1 };
	}

	public ResultSet executeQuery(String sql) throws SQLException {
		mds.checkState();
		return executerHandler.execute("executeQuery", sql);
	}

	protected int updateInternal(String method, String sql) {
		try {
			Thread.sleep(insertSleepTime);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		this.sql = sql;
		MockDataSource.record(new ExecuteInfo(this.mds, method, this.sql, null));
		logger.warn("[UpdateHandler]" + sql);
		return MockDataSource.popPreAffectedRow();
	}

	public int executeUpdate(String sql) throws SQLException {
		mds.checkState();
		return updateInternal("executeUpdate", sql);
	}

	private long insertSleepTime = 0;

	public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
		mds.checkState();
		return updateInternal("executeUpdate#sql_int", sql);
	}

	public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
		mds.checkState();
		return updateInternal("executeUpdate#sql_int[", sql);
	}

	public int executeUpdate(String sql, String[] columnNames) throws SQLException {
		mds.checkState();
		return updateInternal("executeUpdate#sql_string[", sql);
	}

	public Connection getConnection() throws SQLException {
		throw new NotSupportException("");
	}

	public int getFetchDirection() throws SQLException {
		throw new NotSupportException("");
	}

	public int getFetchSize() throws SQLException {
		return this.fetchSize;
	}

	public ResultSet getGeneratedKeys() throws SQLException {
		throw new NotSupportException("");
	}

	public int getMaxFieldSize() throws SQLException {
		throw new NotSupportException("");
	}

	public int getMaxRows() throws SQLException {
		return this.maxRows;
	}

	public boolean getMoreResults() throws SQLException {
		throw new NotSupportException("");
	}

	public boolean getMoreResults(int current) throws SQLException {
		throw new NotSupportException("");
	}

	public int getQueryTimeout() throws SQLException {
		return this.queryTimeOut;
	}

	public ResultSet getResultSet() throws SQLException {
		mds.checkState();
		return new MockResultSet(mds, MockDataSource.popPreData());
	}

	public int getResultSetConcurrency() throws SQLException {
		throw new NotSupportException("");
	}

	public int getResultSetHoldability() throws SQLException {
		throw new NotSupportException("");
	}

	public int getResultSetType() throws SQLException {
		throw new NotSupportException("");
	}

	public int getUpdateCount() throws SQLException {
		throw new NotSupportException("");
	}

	public SQLWarning getWarnings() throws SQLException {
		//throw new NotSupportException("");
		return null;
	}

	public void setCursorName(String name) throws SQLException {
		throw new NotSupportException("");

	}

	public void setEscapeProcessing(boolean enable) throws SQLException {
		throw new NotSupportException("");

	}

	public void setFetchDirection(int direction) throws SQLException {
		throw new NotSupportException("");
	}

	public void setFetchSize(int rows) throws SQLException {
		this.fetchSize=rows;
	}

	public void setMaxFieldSize(int max) throws SQLException {
		throw new NotSupportException("");
	}

	public void setMaxRows(int max) throws SQLException {
		this.maxRows=max;
	}

	public void setQueryTimeout(int seconds) throws SQLException {
		this.queryTimeOut=seconds;
	}

	public String getSql() {
		return sql;
	}

	public void setSql(String sql) {
		this.sql = sql;
	}

	public int getCloseInvokingTimes() {
		return closeInvokingTimes;
	}

	public void setCloseInvokingTimes(int closeInvokingTimes) {
		this.closeInvokingTimes = closeInvokingTimes;
	}

	public boolean isClosed() {
		return isClosed;
	}

	public void setClosed(boolean isClosed) {
		this.isClosed = isClosed;
	}

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public int getExecuteSqlInvokingTimes() {
		return executeSqlInvokingTimes;
	}

	public void setExecuteSqlInvokingTimes(int executeSqlInvokingTimes) {
		this.executeSqlInvokingTimes = executeSqlInvokingTimes;
	}

	public ExecuteHandler getExecuterHandler() {
		return executerHandler;
	}

	public void setExecuterHandler(ExecuteHandler executerHandler) {
		this.executerHandler = executerHandler;
	}

	/*public UpdateHandler getUpdateHandler() {
		return updateHandler;
	}

	public void setUpdateHandler(UpdateHandler updateHandler) {
		this.updateHandler = updateHandler;
	}*/

	public long getInsertSleepTime() {
		return insertSleepTime;
	}

	public void setInsertSleepTime(long insertSleepTime) {
		this.insertSleepTime = insertSleepTime;
	}

	public <T> T unwrap(Class<T> iface) throws SQLException
	{
		// TODO Auto-generated method stub
		return null;
	}

	public boolean isWrapperFor(Class<?> iface) throws SQLException
	{
		// TODO Auto-generated method stub
		return false;
	}

	public void setPoolable(boolean poolable) throws SQLException
	{
		// TODO Auto-generated method stub
		
	}

	public boolean isPoolable() throws SQLException
	{
		// TODO Auto-generated method stub
		return false;
	}

}
